home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2493 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointer Conversion
  5. Date: 21 Jan 1996 23:14:19 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4duhcb$7if@news.iag.net>
  8. References: <4ds4jq$fo4@su3.in.net> <4ds6s3$ft6@su3.in.net>
  9. NNTP-Posting-Host: pm2-orl13.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4ds6s3$ft6@su3.in.net>, poundss@in.net says...
  13. >
  14. >poundss@in.net (Sam Pounds) wrote:
  15. >
  16. >
  17. >>char *my_strcat(const char *a, const char *b)
  18. >>{
  19. >>    char done[1024];
  20. >>    char *p = done;
  21. >
  22. >>    while (*a)
  23. >>      *p++ = *a++;
  24. >>    while (*b)
  25. >>      *p++ = *b++;
  26. >>    *p = '\0';
  27. >>    return done; /* this is the suspicious pointer conversion error */
  28.  
  29. The problem here is that the memory allocated to create done, when this 
  30. function started, is deallocated, when it exits.  So you are returning a 
  31. pointer to an invalid memory location.
  32.  
  33. >>}
  34. >
  35. >Sorry, it just dawned on me.
  36. >char *done = (char *)malloc(1024);
  37. >
  38. >But if anyone could tell me how I could just alloc the
  39. >necessary memory for the two pointers I would appreciate it.
  40. >Sorry again.
  41.  
  42. I'm afraid I don't understand your question.  What two pointers are you 
  43. do you want to allocate memory for?
  44.  
  45. If you want your function to return a pointer to a new array containing the 
  46. concatenated string (instead of concatenating b to a, like in strcat), you 
  47. only have a few options:
  48.  
  49.   1. Define a static char array for the result (either global or using the 
  50.      static storage qaulifier). Since only one char array will exist, its 
  51.      contents will be overwritten on each call to my_strcat.  The caller
  52.      would probably need to strcpy it elsewhere before the next call.
  53.  
  54.   2. Allocate a new dynamic array for the result. This is equivalent to your
  55.      malloc solution. The caller will have to free this memory, when it is 
  56.      no longer needed.
  57.  
  58.   3. Define my_strcat to accept a char pointer to an external array and
  59.      write the result there.  The caller would be responsible for passing
  60.      a valid pointer to a char array of the correct size.
  61.  
  62. -- 
  63. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  64. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  65.  
  66.